class SpringOffset extends egret.Sprite {
    private ball: Ball
    private spring: number = 0.1
    private springLength: number = 100
    private friction: number = 0.95

    private touchX: number = 0
    private touchY: number = 0

    public constructor() {
        super()
        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(event: egret.Event) {
        this.ball = new Ball()
        this.addChild(this.ball)
        this.ball.x = 0
        this.ball.y = 0
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.trackTouch, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: egret.Event) {
        let dx = this.ball.x - this.touchX
        let dy = this.ball.y - this.touchY
        let angle = Math.atan2(dy, dx)
        let targetX = this.touchX + Math.cos(angle) * this.springLength
        let targetY = this.touchY + Math.sin(angle) * this.springLength
        let ax = (targetX - this.ball.x) * this.spring
        let ay = (targetY - this.ball.y) * this.spring
        this.ball.vx += ax
        this.ball.vy += ay
        this.ball.vx *= this.friction
        this.ball.vy *= this.friction
        this.ball.x += this.ball.vx
        this.ball.y += this.ball.vy

        this.graphics.clear()
        this.graphics.lineStyle(1)
        this.graphics.moveTo(this.ball.x, this.ball.y)
        this.graphics.lineTo(this.touchX, this.touchY)
    }

    private trackTouch(evt:egret.TouchEvent) {
        this.touchX = evt.stageX
        this.touchY = evt.stageY
    }
}